package com.power.leopard.common.util;

import java.io.IOException;
import java.net.ServerSocket;

public class NetUtils {

	public static int getAvailablePort(int defaultPort) {
		int port = defaultPort;
		while (port < 65535) {
			if (!isPortInUse(port)) {
				return port;
			} else {
				port++;
			}
		}
		while (port > 0) {
			if (!isPortInUse(port)) {
				return port;
			} else {
				port--;
			}
		}
		throw new IllegalStateException("no available port");
	}

	public static boolean isPortInUse(int port) {
		boolean inUse = true;
		ServerSocket socket = null;
		try {
			socket = new ServerSocket(port);
			inUse = false;
		} catch (IOException e) {
			inUse = true;
		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
				}
			}
		}
		return inUse;
	}

}
